package com.pactera.bledemo.activity.traditional

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Toast
import com.dylanc.viewbinding.nonreflection.binding
import com.pactera.bledemo.base.BaseActivity
import com.pactera.bledemo.databinding.ActivityServerBinding
import com.pactera.library.utils.BleUtils
import com.pactera.library.listener.OnDataReceiveServerSocketListener
import java.io.InputStream
import java.lang.Exception
import java.util.*

class ServerActivity : BaseActivity() {
    private val binding by binding(ActivityServerBinding::inflate)

    private val NAME = "Bluetooth_Socket"
    private val MY_UUID = UUID.fromString("abcd1234-ab12-ab12-ab12-abcdef123456") //和客户端相同的UUID
    private var serverSocket: BluetoothServerSocket? = null
    private var socket: BluetoothSocket? = null
    private var inputStream: InputStream? = null //输入流
    private var acceptThread: AcceptThread? = null
    lateinit var defaultAdapter: BluetoothAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.tvTip.text = "接受到的客户端发送过来的数据为："
        /* acceptThread = AcceptThread()
         acceptThread?.start()*/

        //推荐此方法：在单例模式下，就行开启读取线程，哪里想接受数据，哪里复写此监听方法即可。
        ble.setOnDataReceiveServerSocketListener(object : OnDataReceiveServerSocketListener {
            override fun onDataReceive(result: String?) {
                runOnUiThread {
                    Log.i(TAG, "handleMessage: result=$result")
                    binding.tvResult.append(result + "\n")
                    Toast.makeText(applicationContext, result, Toast.LENGTH_LONG).show()
                }
            }
        })

    }


    private val handler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            val result = msg.obj.toString()
            Log.i(TAG, "handleMessage: result=$result")
            binding.tvResult.append(result + "\n")
            Toast.makeText(applicationContext, result, Toast.LENGTH_LONG).show()

        }
    }

    //服务端监听客户端的线程类
    public inner class AcceptThread : Thread() {
        init {
            try {
                serverSocket = defaultAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        override fun run() {
            try {
                socket = serverSocket?.accept()
                inputStream = socket?.getInputStream()
                while (true) {
                    val buffer = ByteArray(1024)
                    val count: Int? = inputStream?.read(buffer)
                    val msg = Message()
                    msg.obj = String(buffer, 0, count ?: 0, charset("utf-8"))
                    handler.sendMessage(msg)
                }
            } catch (e: Exception) {
                Log.i(TAG, "run: 异常 msg=${e.message}")
            }
        }
    }

    fun closeConnect() {
        try {
            serverSocket?.close()
            socket?.close()
            socket = null
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            BleUtils.i(TAG, "异常 msg=$e")
        } finally {
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        closeConnect()
        mBluetoothAdapter?.cancelDiscovery()
    }


}